import { useState, createContext } from "react"
import Menu from "./menu/index.jsx"
import { useEffect } from "react"
import axios  from 'axios'
/***
 * 后代组件传参
 * 1.首先使用creatContext函数创建一个ThemeContext上下文，并导出，后代组件需要导入使用
 * 2.用ThemeContext.Provide 组件包裹需要传参的后代组件，并写入value属性和传递对应的值
 * 3.子组件通过导入父组件创建的 { ThemeContext } 上下文，传入 userContext函数中使用，即可拿到父组件的数据
 */
export const ThemeContext = createContext()
function App() {
  const [color, setColor] = useState("pink")
  const [menuList,setMenuList] = useState()

  // 子组件通信
  const onSelectMenuItem = (id) => {
    // console.log(id) // 子组件传递的数据
  }

  // 后代组件通信
  const setColorHandle = (e) => {
    setColor(e.target.value)
  }

  // 后端组件通信重置颜色
  const resetColorHandle = ()=>{
    setColor('pink')
  }

  // 获取menu列表
  const getMenuList = async ()=>{
    const res = await axios.get('http://localhost:8080/list')
    setMenuList(res.data)
  }

  // 点赞收藏
  const onlikeHandle = async (id,like)=>{
      like = !like
      const res = await axios.patch( `http://localhost:8080/list/${id}`,{like})
      getMenuList()
  }
  
  const editPriceHandle = async (data)=>{
    const res = await axios.patch( `http://localhost:8080/list/${data.currentId}`,{price:data.editPrice})
    getMenuList()
  }

  useEffect(()=>{
    getMenuList()
  },[])
  return (
    <div id="app">
      <input type="color" onChange={setColorHandle} />
      <ThemeContext.Provider value={{color,resetColorHandle}}>
        {
          menuList && <Menu
          menuList={menuList}
          onSelectMenuItem={onSelectMenuItem}
          onlikeHandle={onlikeHandle}
          editPriceHandle={editPriceHandle}
        />
        }
      </ThemeContext.Provider>
    </div>
  )
}

export default App
